<template>
	<view class="container">
		<view class="container">
			<view class="bind_card" v-if="merchantNumber">
				<view class="title">
					<image src="../../static/icon/bangka.png"></image>
					<text>NFC检测到商户信息</text>
				</view>
				<view class="card-item">
					<view>
						商户账户：{{merchantNumber}}
					</view>
					<view>
						商户名称：{{merchantName}}
					</view>					
				</view>							
				<view>
					<input type="number" placeholder="输入支付金额" class="amount" v-model="amount">
				</view>
			</view>			
			<button type="primary" @click="pay" v-if="merchantNumber">进入支付页面</button>
			<image src="../../static/icon/nfc.png" class="nfc-img" mode="center"></image>
		</view>	
	</view>
</template>

<script>
	var NfcAdapter;
	var NdefRecord;
	var NdefMessage;
	var waiting
	var readyRead = false;
	var nfcAdapter, main, pendingIntent, intentFiltersArray, techListsArray, IntentFilter

	export default {
		data() {
			return {
				merchantNumber:'',
				merchantName:'',
				amount:'',
				currentNFCInfo: '嘎嘎', //NFC 读取消息；  
				bannerShow: false,
				remark: "",
				message: "",
				count: 0,
				timestampHide: "",
				timestampShow: "",
				payLimit:''
			};
		},
		methods: {
			listenNFCStatus() {
				try {
					console.log('Init NFC...');
					main = plus.android.runtimeMainActivity();
					var Intent = plus.android.importClass('android.content.Intent');
					var Activity = plus.android.importClass('android.app.Activity');
					var PendingIntent = plus.android.importClass('android.app.PendingIntent');
					IntentFilter = plus.android.importClass('android.content.IntentFilter');
					NfcAdapter = plus.android.importClass('android.nfc.NfcAdapter');
					nfcAdapter = NfcAdapter.getDefaultAdapter(main);
					var intent = new Intent(main, main.getClass());
					intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					pendingIntent = PendingIntent.getActivity(main, 0, intent, 0);
					var ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
					ndef.addDataType("*/*");
					intentFiltersArray = [ndef];
					techListsArray = [
						["android.nfc.tech.IsoDep"],
						["android.nfc.tech.NfcA"],
						["android.nfc.tech.NfcB"],
						["android.nfc.tech.NfcF"],
						["android.nfc.tech.Ndef"],
						["android.nfc.tech.NfcV"],
						["android.nfc.tech.NdefFormatable"],
						["android.nfc.tech.MifareClassic"],
						["android.nfc.tech.MifareUltralight"]
					];

				} catch (e) {
					console.error(e);
				}
			},
			handle_nfc_data() {

				NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
				NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
				// main = plus.android.runtimeMainActivity();  
				var intent = main.getIntent();

				console.log("action type:" + intent.getAction());
				if ("android.nfc.action.TECH_DISCOVERED" == intent.getAction()) {
					if (readyRead) {
						this.__read(intent);
						readyRead = false;
					}
				} else {
					// waiting.close();  
					console.log("nfc读取失败")
				}
			},
			__read(intent) {
				try {					
					var content = "";
					waiting = plus.nativeUI.showWaiting("请将NFC标签靠近！");
					waiting.setTitle('请勿移开标签\n正在读取数据...');
					var tag = plus.android.importClass("android.nfc.Tag");
					waiting.close();
					var Parcelable = plus.android.importClass("android.os.Parcelable");
					// var rawmsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");  
					var rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

					if (rawmsgs != null && rawmsgs.length > 0) {
						waiting.close();
						// console.log(JSON.stringify(rawmsgs[0]));  
						var records = rawmsgs[0].getRecords();
						var result = records[0].getPayload();
						// console.log(result)  
						if (result != null) {
							var s = plus.android.newObject("java.lang.String", result);
							console.log(s);
							
							//读取到IC卡数据（注意截取起始空白符）							
							if (s.charCodeAt(1) == 65279)
								this.currentNFCInfo = s.substring(2)
							else
								this.currentNFCInfo = s.substring(1)													
							
							// console.log('数据类型',typeof this.currentNFCInfo)
							console.log('内容' + this.currentNFCInfo)
							// console.log('长度' + this.currentNFCInfo.length)
																												
							//解析json串
							let json = JSON.parse(this.currentNFCInfo)
														
							//如果成功读取商户信息 
							if (json && json.merchantnumber) {
								this.merchantNumber = json.merchantnumber;
								this.merchantName = json.merchantname;
							} else {
								this.merchantNumber = '';
								this.merchantName = '';
							}
						} else {
							this.currentNFCInfo = "";
						}
						
						plus.nativeUI.closeWaiting()
					} else {
						console.log("NFC获取失败");
						uni.showToast({
							title: "NFC获取失败.",
							icon: "none"
						});
					}

				} catch (e) {
					console.log(e);
					console.log("NFC获取失败,丢出异常");
					waiting.close();
					uni.showToast({
						title: "NFC获取失败",
						icon: "none"
					});
					//TODO handle the exception  
				}
			},
			readData() {
				readyRead = true;
				waiting = plus.nativeUI.showWaiting("检测到NFC，正在读取数据请勿离开");  
				setTimeout(this.handle_nfc_data, 1000);
			},
			//进入支付详情页面
			pay(){
				//验证支付限额
				if (parseFloat(this.amount) > parseFloat(this.payLimit)) {
					uni.showToast({
						title:'当前支付超出支付限额，请先修改支付限额',
						icon:'none'
					})
					
					return
				}
				
				uni.navigateTo({
					url:'../pay_detail/pay_detail?merchantNumber=' + this.merchantNumber +
						'&amount=' + this.amount
				})			
			}
		},
		onLoad: function(option) {
			this.listenNFCStatus()
			//读取支付限额
			this.payLimit = uni.getStorageSync('payLimit')
		},
		onShow: function() {
			console.log('page Show');
			this.timestampShow = (new Date()).getTime();
			console.log(this.timestampShow)
			var TimeScale = this.timestampShow - this.timestampHide;
			console.log(TimeScale);
			nfcAdapter.enableForegroundDispatch(main, pendingIntent, intentFiltersArray, techListsArray);
			if (this.count++ == 0) {
				// this.listenNFCStatus()  
				return false;
			} else if (TimeScale > 400) {
				return false;
			} else {
				this.readData();
			}
		},
		onHide: function() {
			console.log("onHide");
			this.timestampHide = (new Date()).getTime();
			console.log(this.timestampHide);
		}
	}
</script>
<style>
	page {
		background: #EDEDED;
	}
	
	.container {
		padding: 15rpx;
	}
	
	.bind_card {
		padding: 30rpx;
		font-size: 30rpx;		
		background-color: #FFFFFF;
		border-radius: 25rpx;
		margin-bottom: 30rpx;
	}
	
	.bind_card .title {
		color: #333333;
		font-weight: bold;
		height: 80rpx;
		line-height: 80rpx;			
	}
	
	.bind_card .title image {
		width: 80rpx;
		height: 80rpx;
		float: left;
	}
	
	.bind_card .title text {
		float: left;
		padding-left: 40rpx;
	}
	
	.bind_card .card-item {
		color: #FFFFFF;
		background: #66CCFF;
		padding: 10rpx;
		margin-bottom: 20rpx;
		border-radius: 15rpx;
		line-height: 50rpx;
	}
	
	.amount {
		width: 600rpx;
		height: 150rpx;
		color: #333333;
		font-size: 48rpx;
		border-bottom: 1px solid #C0C0C0;
		margin-bottom: 50rpx;
	}
	
	button {
		margin-top: 20rpx;
	}	
	
	.nfc-img {
		width: 600rpx;
		display: block;
		margin: 0 auto;
	}
</style>